
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
class food {
  /**
     * @swagger
     * components:
     *   schemas:
     *     Food:
     *       type: object
     *       properties:
     *         fid:
     *           type: integer
     *         name:
     *           type: string
     *         composition:
     *           type: string
     * 
     * /food:
     *   get:
     *     tags: [Корм]
     *     summary: Получение списка кормаов
     *     responses:
     *       200:
     *         description: Список кормов
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 foods:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/Food'
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async foodGet (req, res) {
          try {
        
            const queryText = `
              SELECT * FROM food;
            `;
        
            const result = await pool.query(queryText);
            const foods = result.rows;
        
        
            const response = {
                foods,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
    /**
     * @swagger
     * /food:
     *   post:
     *     tags: [Корм]
     *     summary: Создание нового корма
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               name:
     *                 type: string
     *               composition:
     *                 type: string
     *     responses:
     *       200:
     *         description: Новый корм питания создан
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Food'
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async foodPost (req, res){
          try {
            const { name, composition } = req.body;
        
            const queryText = `
              INSERT INTO food (name, composition)
              VALUES ($1, $2)
              RETURNING *;
            `;
            const values = [name, composition];
        
            const result = await pool.query(queryText, values);
            const newFood = result.rows[0];
        
            res.json(newFood);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
}

module.exports = new food()